package device

import (
	"encoding/json"
	"errors"
	"reflect"
	"time"
)

// 延时 {"time":1543309254,"start":1,"end":1,"order":1,"loop":1,"state":0,"tasknoc":"5bfbb49bc175f46d4e15342b"}
type Delay struct {
	Command
	Start int `json:"start"` // 打开时间（分钟） 例如： 12 打开时间和关闭时间至少填写一项
	End   int `json:"end"`   // 关闭时间（分钟） 例如： 12
	Order int `json:"order"` // 0代表先开后关 1代表先关后开
	Loop  int `json:"loop"`  // 循环次数 默认值为0 0代表无限循环
	State int `json:"state"` // 0关闭指令 1 开启指令
}

func (d *Delay) Parser(m interface{}, action int) error {
	if reflect.ValueOf(m).Type().String() != "*models.Delay" {
		return errors.New("m Must be *models.Delay struct.")
	}

	d.Type = TYPE_DELAY
	d.Time = time.Now().Unix()
	d.Start = int(reflect.ValueOf(m).Elem().FieldByName("Start").Int())
	d.End = int(reflect.ValueOf(m).Elem().FieldByName("End").Int())
	d.Tasknoc = reflect.ValueOf(m).Elem().FieldByName("Id").String()
	d.Order = int(reflect.ValueOf(m).Elem().FieldByName("Order").Int())
	d.Done = CreateSign()
	d.State = int(reflect.ValueOf(m).Elem().FieldByName("State").Int())
	d.Loop = int(reflect.ValueOf(m).Elem().FieldByName("Loop").Int())
	d.Action = int64(action)

	return nil
}

func AddDelay(delay interface{}) error {
	return sendDelay(INSERT, delay)
}

func UpdateDelay(delay interface{}) error {
	return sendDelay(UPDATE, delay)
}

func DeleteDelay(delay interface{}) error {
	return sendDelay(DELETE, delay)
}

func sendDelay(action int, delay interface{}) error  {
	dl := Delay{}
	err := dl.Parser(delay, action)
	if err != nil {
		return err
	}

	payload, err := json.Marshal(dl)
	if err != nil {
		DelSign(dl.Done)
		return err
	}

	return dl.SendCommand(reflect.ValueOf(delay).Elem().FieldByName("Sta").String(), string(payload), 1, false)
}
